<?php
class NEWS
{

	//获取总数
	static public function TOTAL($where) {
		$CacheKey	= "__Total_" . $where ;
		if ( __NEWS_CACHE_OFF__ != 0 )
		{
			$CacheData = XINHUA::memcached('r')->get($CacheKey);
			if ( !empty($CacheData)	)
			{	
				return $CacheData;
			}
		}		

		$objcms		= XINHUA::mysql('r' , 'cms');
		$showsql	= "SELECT count(1) as num FROM `xuanwen` WHERE {$where}";

		$data	= $objcms->query( $showsql )->fetch( PDO::FETCH_ASSOC );
		if ($data)
		{
			if ((int)$data['num'] > 0 && __NEWS_CACHE_OFF__ != 0 )
			{
				XINHUA::memcached('r')->set($CacheKey, (int)$data['num'], __NEWS_LIFE_TIME__);
			}	
			return $data['num'];
		}	
		return 0;
	}

	//初始化返回数据
	static public function LISTDATA( $where,$offset = 20 , $page=1, $option = array(), $channelid = 0,  $productid='', $useragent='')
	{
		$_preg		= '/^http(s)?:\/\//';
		$CacheKey	= __NEWS_LIST__.$where . $page;
		if( __NEWS_CACHE_OFF__ != 0 )
		{
			$CacheData = XINHUA::memcached('r')->get($CacheKey);
			if(!empty($CacheData))
			{
				return unserialize( $CacheData );
			}
		}

		$pageNum = (($page-1)*$offset);
		$callback	= array();
		$objcms		= XINHUA::mysql('r' , 'cms');
		$cloumn		= "`catid`,`id`,`shorturl`,`title`,`url`,`description`,`foottype`,`showtype`,`area`,`newstype`,`thumb`,`bigthumb`,`created`,`updated`,`published`,`listorder`,`iscomment`, `liveurl`, `extra`";
		$showsql	= "SELECT {$cloumn} FROM `xuanwen` WHERE {$where} ORDER BY `published` DESC LIMIT {$pageNum}, {$offset}";

		$data	= $objcms->query( $showsql )->fetchAll( PDO::FETCH_ASSOC );
		if ($data)
		{
			foreach ($data as $v) {

				$source = self::getExtraValue('source', $v['extra']);
				$source = empty($source) ? "新华网" : $source;

				$callback[]	= array(
								'newsId'		=> (string)$v['id'],
								'title'			=> !empty($v['title']) ? (string)$v['title'] : '',
								/*
								'newsType'		=> $v['newstype'],
								'commentcount'	=> 0,
								'iscomment'		=> 0,
								'orders'		=> (int)$v['listorder'],
								'picInfo'		=> array(),
								'minipics'		=> array(),
								'created'		=> !empty($v['created']) ? $v['created'] : '',
								'updated'		=> !empty($v['updated']) ? $v['updated'] : '',
								*/
								'published'		=> !empty($v['published']) ?$v['published'] : '',
								//'liveurl'       => !empty($v['liveurl']) ? $v['liveurl'] : '',
								'showSource'    => $source,
								//'vrvideourl'    => '',
							);
			}
			
		}
		if( __NEWS_CACHE_OFF__ != 0 )
		{
			
			XINHUA::memcached('r')->set($CacheKey, serialize($callback), __NEWS_LIFE_TIME__);
		}
		return $callback;
	}

	static function recommendTotal($where, $channelid) {
		$CacheKey	= "__RE_Total_" . $where ;
		if ( __NEWS_CACHE_OFF__ != 0 )
		{

			$CacheData = XINHUA::memcached('r')->get($CacheKey);
			if ( !empty($CacheData)	)
			{	
				return $CacheData;
			}
		}

		
		$objcms		= XINHUA::mysql('r' , 'cms');
		$sql		= "SELECT `posid`,`type`,`listorder` FROM `position` WHERE {$where}  ORDER BY `listorder` ASC ";
		$position	= $objcms->query( $sql )->fetchAll( PDO::FETCH_ASSOC );

		if($position) {
			$other = array();
			$all = array();
			$newsIds = array();
			foreach ($position as $v) {

				$other[$v['posid']] = $v['posid'];
				$all[$v['posid']] = $v['posid'];
				$newsIds[$v['posid']] = $v['posid'];
			}//end foreach

			$where = "b.`id`=p.`id` AND p.`catid`={$channelid} AND b.`newstype`=0  AND p.`posid`=" . implode(" OR p.`posid`=", $all);
			$sql1 = "SELECT count(1) as num FROM `position_data` p , `xuanwen` b WHERE {$where}";

			$d = $objcms->query($sql1)->fetch(PDO::FETCH_ASSOC);

			if ($d) {
				if ( (int)$d['num'] > 0 && __NEWS_CACHE_OFF__ != 0 )
				{
					XINHUA::memcached('r')->set($CacheKey, (int)$d['num'], __NEWS_LIFE_TIME__);
				}	

				return $d['num'];
			}
			
		}

		return 0;	


	}//end recommendTotal

	static public function RECOMMEND( $where ,$offset = 20 , $page=1, $option = array(), $channelid, $productid='',$useragent=''){
		$CacheKey	= __NEWS_LIST__. "re_" .$where . $page ;
		if( __NEWS_CACHE_OFF__ != 0 )
		{
			$CacheData = XINHUA::memcached('r')->get($CacheKey);
			if(!empty($CacheData))
			{
				return unserialize( $CacheData );
			}
		}


		$pageNum = (($page-1)*$offset);
		$callback	= array();
		$objcms		= XINHUA::mysql('r' , 'cms');
		$sql		= "SELECT `posid`,`type`,`listorder` FROM `position` WHERE {$where}  ORDER BY `listorder` ASC ";
		$position	= $objcms->query( $sql )->fetchAll( PDO::FETCH_ASSOC );
		if($position) {

			$other = array();
			$all = array();
			$newsIds = array();
			foreach ($position as $v) {

				$other[$v['posid']] = $v['posid'];
				$all[$v['posid']] = $v['posid'];
				$newsIds[$v['posid']] = $v['posid'];
			}

			$where = "b.`id`=p.`id` AND p.`catid`={$channelid} AND b.`newstype`=0  AND p.`posid`=" . implode(" OR p.`posid`=", $all);
			$sql1 = "SELECT p.`id`, p.`data`,p.`posid`,b.`extra` FROM `position_data` p , `xuanwen` b WHERE {$where} ORDER BY p.`listorder` ASC LIMIT {$pageNum}, {$offset}";
// 			@error_log( "\n position_data_sql=$sql1",3,'/tmp/pzrlog.log');
			$datalist = $objcms->query($sql1)->fetchAll(PDO::FETCH_ASSOC);
			if ($datalist) {
				foreach ($datalist as $v) {
					$source = self::getExtraValue('source', $v['extra']);
					$source = empty($source) ? "新华网" : $source;
					$json = json_decode($v['data'], true);
					$callback[] = array(

						'newsId' => (string)$v['id'],
						//'posid' => (int)$v['posid'],
						'title' => !empty($json['title']) ? (string)stripslashes(urldecode($json['title'])) : '',
						//'thumbnail' => !empty($json['thumb']) ? strpos(urldecode($json['thumb']), __STATIC_REPLACE_URL__) === 0 ? urldecode($json['thumb']) : (__STATIC_IMAGE_URL__ . urldecode($json['thumb'])) : '',
						//'description' => !empty($json['description']) ? (string)stripslashes(urldecode($json['description'])) : '',
						'published' => !empty($json['inputtime']) ? (string)stripslashes(urldecode($json['inputtime'])) : '',
						'showSource'    => $source,

					);
				}
			}
		}


		if( __NEWS_CACHE_OFF__ != 0 )
		{
			//XINHUA::redis('w')->setex( $CacheKey, __NEWS_LIFE_TIME__, $callback );
			XINHUA::memcached('r')->set($CacheKey, serialize($callback), __NEWS_LIFE_TIME__);
		}
		return $callback;

	}
	static public function DETAIL( $newsid=0 )
	{
		 	$CacheKey	= __NEWS_DETAIL__ . $newsid;
			if( __NEWS_CACHE_OFF__ != 0 )
			{
				$CacheData   = XINHUA::memcached('r')->get($CacheKey);
				if(!empty($CacheData))
				{
					return  unserialize($CacheData);
				}				
			}			 	

			$objcms		= XINHUA::mysql('r' , 'cms');
		 	$sql		= "SELECT * FROM `xuanwen` WHERE `id`={$newsid} AND `status`=2 AND `isdelete`=1 AND `isdisplay`=0  LIMIT 1";
			$xuanwen	= $objcms->query( $sql )->fetch(PDO::FETCH_ASSOC);
			if(!$xuanwen)
			{
				return array('title' => '无', 'published' => 0, 'mcontent' => '', 'source' => '新华网');
			}

			$showdata	= array();
			$sql1		= "SELECT * FROM `xuanwen_data` WHERE `id`={$newsid} LIMIT 1";
			$xuanwendata= $objcms->query( $sql1 )->fetch( PDO::FETCH_ASSOC );
			$backdata = array();
			if(!empty($xuanwendata))
			{
				$mcontent  = $xuanwendata['mcontent'];
                
                //$mcontent = preg_replace_callback('/<!--IMG#(\d*)-->/', $this->replaceimg, $mcontent);
                $mcontent = self::replaceimage($xuanwendata['pics'], $mcontent);
                /*
                $xuanwendata['mcontent'] = $mcontent;
				$showdata	= $xuanwendata;
				$showdata['published'] = $xuanwen['published'];
				$showdata['title']     = $xuanwen['title'];
				*/

				$backdata['mcontent']  = $mcontent;
				$backdata['published'] = $xuanwen['published'];
				$backdata['title']     = $xuanwen['title']; 
				$backdata['source']    = $xuanwendata['source'];
			}

			if( __NEWS_CACHE_OFF__ != 0 )
			{
				
				XINHUA::memcached('r')->set($CacheKey, serialize($backdata), __NEWS_LIFE_TIME__);
			}

			return $backdata;
	}

	static public function replaceimage($pics, $subject) 
	{
		$json     = json_decode($pics,true);
		if (empty($json))
		{
			return $subject;
		}	
		$pattern = '/<!--IMG#(\d*)-->/';
		preg_match_all($pattern, $subject, $matches);
		if ($matches)
		{

			$img_arr = $matches[0];
			$pos_arr = $matches[1];
			$count   = count($img_arr);
			for ($i=0; $i<$count; $i++)
			{
				$key = $pos_arr[$i];
				$subject = str_replace($img_arr[$i], "<img src=\"". __CONTENT_STATIC_URL__. $json[$key]['fileurl'] . "\"/>" , $subject);
			}	

		}
		return $subject;		
	}

	static public function replaceimg($key) 
	{
    	$json     = json_decode($GLOBALS['xuanwendata']['pics'],true);
    	$showpics = array();
    	foreach($json as $k=>$v)
    	{
      		$showpics[$k] = !empty($v['fileurl']) ?  (__CONTENT_STATIC_URL__.$v['fileurl']) : '';
    	}
    	
    	return !empty($showpics[$key[1]]) ? '<div style="width:100%;overflow:hidden;clear:both;text-align:center;"><img width="90%" align="middle" src="'.$showpics[$key[1]].'" /></div>' : '';	
    }

	static public function getExtraValue($keyParam, $extra)
	{
		if (empty($extra) || empty($keyParam))
		{
			return '';
		}	
		
		$json  = json_decode($extra, true);
		if ($json && isset($json[$keyParam]))
		{
			return $json[$keyParam];
		}
		return '';
	}

	
}

